package com.cybertron.ironhide.manage.service.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.cybertron.ironhide.manage.common.base.Pager;
import com.cybertron.ironhide.manage.common.jms.sender.SeedUrlMessageSender;
import com.cybertron.ironhide.manage.domain.Alliance;
import com.cybertron.ironhide.manage.domain.SeedUrl;
import com.cybertron.ironhide.manage.persistence.AllianceMapper;
import com.cybertron.ironhide.manage.persistence.SeedUrlMapper;
import com.cybertron.ironhide.manage.service.AllianceService;
import com.cybertron.ironhide.manage.util.CommonUtil;
import com.cybertron.ironhide.manage.util.FileUtil;

@Service
public class AllianceServiceImpl implements AllianceService {

	@Resource
	private AllianceMapper allianceMapper;

	@Resource
	private SeedUrlMapper seedUrlMapper;

	@Resource
	private SeedUrlMessageSender messageSender;

	@Override
	public List<Alliance> selectBySelective(Alliance record, Pager pager) {
		return allianceMapper.selectBySelective(record, pager);
	}

	@Override
	public void insertSelective(Alliance record) {
		record.setId(CommonUtil.getUUID());
		record.setLogo(FileUtil.moveAlianceLogoFile(record.getTitle(),
				record.getLogo()));
		record.setTitle(StringUtils.lowerCase(record.getTitle()));
		record.setCreateDate(new Date());
		record.setModifyDate(new Date());
		allianceMapper.insertSelective(record);
	}

	@Override
	public void deleteByPrimaryKey(String id) {
		allianceMapper.deleteByPrimaryKey(id);
	}

	@Override
	public Alliance selectByPrimaryKey(String id) {
		return allianceMapper.selectByPrimaryKey(id);
	}

	@Override
	public void updateByPrimaryKeySelective(Alliance record) {
		record.setLogo(FileUtil.moveAlianceLogoFile(record.getTitle(),
				record.getLogo()));
		record.setTitle(StringUtils.lowerCase(record.getTitle()));
		record.setModifyDate(new Date());
		allianceMapper.updateByPrimaryKeySelective(record);
	}

	@Override
	public boolean checkTitle(String title) {
		Alliance alliance = allianceMapper.selectByTitle(title);
		if (alliance != null) {
			return true;
		}
		return false;
	}

	@Override
	public void insertTaskSelective(String id) {
		Alliance alliance = allianceMapper.selectByPrimaryKey(id);
		if (alliance == null) {
			return;
		}
		List<SeedUrl> seedUrls = seedUrlMapper.selectByHost(alliance.getHost());
		if (seedUrls != null && seedUrls.size() != 0) {
			for (SeedUrl seedUrl : seedUrls) {
				messageSender.sendMsg(seedUrl);
			}
		}
	}
}
